#include "UserRelationDatabase.h"

UserRelationDatabase::UserRelationDatabase()
{
    DatabaseLock lock(this);
    QSqlQuery query;

    // Check if user_auth table already exists
    query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='user_relation'");

    // If query returns a value, the table already exists and initialization can be skipped
    if (query.next())
        return;

    // Create table to hold user health records
    query.exec("CREATE TABLE IF NOT EXISTS user_relation ("
               "relationId INTEGER PRIMARY KEY AUTOINCREMENT, "
               "userId INTEGER, "
               "relatedUserId INTEGER)");
}

void UserRelationDatabase::addRelation(int userId, int userIdRelated)
{
    DatabaseLock lock(this);
    QSqlQuery query;

    query.prepare("INSERT INTO user_relation (userId, relatedUserId)"
                  "VALUES (:userId, :userIdRelated) ");
    query.addBindValue(userId);
    query.addBindValue(userIdRelated);
    query.exec();
}

void UserRelationDatabase::loadRelatedUsers(int userId)
{
    userIds.clear();

    DatabaseLock lock(this);
    QSqlQuery query;

    query.prepare("SELECT relatedUserId FROM user_relation "
                  "WHERE userId=:userId");
    query.addBindValue(userId);
    query.exec();

    while(query.next())
    {
        userIds.push_back(query.value(0).toInt());
    }
}

QList<int> * UserRelationDatabase::getRelatedList()
{
    return &userIds;
}
